package sensornetwork.sensor;

import snifc.sensor.SensorIfc;
import sensornetwork.sensor.Memory;
import sensornetwork.sensor.Queue;
import sensornetwork.sensor.Captor;
import snifc.sensor.IOPortsIfc;
import sensornetwork.Packet;
import java.lang.InterruptedException;


public class Sensor implements SensorIfc {
	
	Memory memory;
	Captor captor;
	Queue queue;
	IOPortsIfc port;
  private int idSensor;
	
	public Sensor (int idSensor, int tailleQueue, int tailleLien, int tailleMemoire, int ttlMax) {
		this.idSensor = idSensor;
    this.memory = new Memory(idSensor, tailleMemoire);
		this.captor = new Captor(idSensor, ttlMax);
		this.queue = new Queue(tailleQueue);
		this.port = new IOPorts(this, tailleLien);
	}
	
	public void simulateCapture(){
    captor.triggerCapture();
	}
	
	public void activateCaptor() {
		try {
      Packet newpacket = (Packet) captor.capture();
      this.queue.enQueue(newpacket);
    } catch (Exception e) {
      //~ System.out.println(e.getMessage()); 
		}
	}
    
	public void activatePort(){
    port.getPackets();
	} 
	
	public void activateQueue(){
    Packet p;
    try {
      if ((p = (Packet) queue.deQueue()) == null) {
        //~ throw new Exception("La file d'attende du sensor # "+this.idSensor+" est vide");
      } else {
        if (!memory.store(p)){
          throw new Exception("Paquet n "+p.getId()+" deja memorise par le sensor # "+this.idSensor);
        }
        if (p.isTimeToLiveOK()) {
          p.ttlDecrement();
          port.writePacket(p);
        } else {
          System.out.println("TTL = 0 packet droped on sensor # "+idSensor);
        }
      }
    } catch (Exception e) {
      System.out.println(e.getMessage());
    }
	}
	
	public String toString() {
    
		return (this.memory.toString()+"\n"+this.queue.toString(idSensor)+"\n---");
	}
	
	public IOPortsIfc getPort(){
    return (port);
	}
  
  public int getId() {
    return idSensor;
  }
}
